package com.fanyouzhao.ehome.web.listener;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

/**
 * @author: fanyouzhao
 * @Date: 11:41 2021/4/30
 */
// 监听器向服务器中注册:
// 1. 在web.xml 中配置
/*<listener>
<listener-class>com.gxa.ehome.web.listener.CountListener</listener-class>
</listener>*/
//2. 使用注解注册: 可以省略value, 甚至不写, 当不写的时候value就是类名
@WebListener
public class CountListener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener, ServletRequestAttributeListener {

    // Public constructor is required by servlet spec
    public CountListener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation`
    // -------------------------------------------------------
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        // 从数据库中查询一部分初始化数据, 让页面访问速度加快
        // 省份/ 城市/ 区县
        // 所有用户数据


//        System.out.println("contextInitialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
//        System.out.println("contextDestroyed");
    }

    int count = 0;
    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */

        //当session被创建一次,就记录一个人数的+1
        count++;

        // 还要能被全局访问 ServletContext
        ServletContext servletContext = se.getSession().getServletContext();
        servletContext.setAttribute("count",count);

        System.out.println("Session is created");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        System.out.println("Session is destroyed");
        count--;
        // 还要能被全局访问 ServletContext
        ServletContext servletContext = se.getSession().getServletContext();
        servletContext.setAttribute("count",count);
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is added to a session.
      */
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attibute
         is replaced in a session.
      */
    }
}
